<template>
  <AdaptiveNavBar title="班期管理" :showBack="true" :showHome="false" />
  <view class="content-area" :style="{ marginTop: $navbarUtil.getNavbarTotalHeightRpx() }">
    <view class="camp-management-container">
      <!-- 主要内容区域 -->
      <view class="content-container">
        <!-- 产品信息卡片 -->
        <view class="section">
          <ProductCard :info="productInfo"></ProductCard>

          <!-- 班期选择区域 -->
          <view class="section-header">
            <view class="header-content header-content-bold">
              <text class="header-content header-content-bold">班期选择</text>
            </view>
          </view>
          <DateCard :dates="datelist" :activeIndex="-1" @change="dateChange"></DateCard>
        </view>

        <!-- 已选班期显示区域 -->
        <view class="section">
          <view class="section-header section-header-wrap">
            <view class="header-full">
              <view class="header-content header-content-bold">
                <text>{{ isDate.id ? '已选班期' : '请选择班期' }}</text>
                <text class="selected-date-text">{{ isDate.Datevalue }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 协作/调用名额审批列表（有班期且有审批数据时显示） -->
        <view v-if="isDate.id && wGroup.length > 0" class="section">
          <view class="section-header">
            <view class="header-content header-content-bold">
              <text>协作/调用名额审批</text>
            </view>
          </view>

          <!-- 商家审批信息列表 -->
          <block v-for="item in wGroup" :key="item.id">
            <view class="merchant-info-section">
              <block v-for="(it, idx) in item.DaiThroughNumber" :key="idx">
                <!-- 分隔线（非首项时显示） -->
                <view v-if="idx !== 0" class="section-divider"></view>

                <!-- 商家基本信息 -->
                <view class="merchant-header">
                  <view class="merchant-type-tag">{{ item.StandbyFieldThree || '组团' }}</view>
                  <text class="merchant-name-text">{{ it.merchantDTO.name }}</text>
                </view>

                <!-- 客源城市信息 -->
                <view class="info-row">
                  <text class="info-label">客源城市</text>
                  <text class="info-value">{{ item.Address }}此处暂无</text>
                </view>

                <!-- 申请名额和操作按钮 -->
                <view class="merchant-footer">
                  <view class="quota-info">
                    <text class="info-label">申请名额</text>
                    <text class="info-value">{{ item.period.fullNumberOfPeople }}人/{{ item.period.fullNumberOfRegiment
                      }}团</text>
                  </view>
                  <button class="action-button" :data-id="item.period.id" :data-merchantId="it.targetMerchantId"
                    :data-relationId="it.id" :data-goType="'答复申请'" @tap="goItem">答复申请</button>
                </view>
              </block>
            </view>
          </block>
        </view>

        <!-- 已同意列表 -->
        <view v-if="isDate.id && jGroup.length > 0" class="section">
          <view class="section-header">
            <view class="header-content header-content-bold">
              <!-- <image class="header-icon-small" role="img" src="https://wxapi.qctrips.cn/yx/images/goods/date.png" mode="" />-->
              <text>已答复的申请</text>
            </view>
          </view>

          <!-- 已答复的申请信息列表 -->
          <block v-for="item in jGroup" :key="item.id">
            <view class="merchant-info-section">
              <block v-for="(it, idx) in item.ThroughNumber" :key="idx">
                <!-- 分隔线（非首项时显示） -->
                <view v-if="idx !== 0" class="section-divider"></view>

                <!-- 商家基本信息 -->
                <view class="merchant-header">
                  <view class="merchant-type-tag">{{ item.StandbyFieldThree || '组团' }}</view>
                  <text class="merchant-name-text">{{ it.merchantDTO.name }}</text>
                </view>

                <!-- 客源城市信息 -->
                <view class="info-row">
                  <text class="info-label">客源城市</text>
                  <text class="info-value">{{ item.Address }}此处暂无</text>
                </view>

                <!-- 申请名额和操作按钮 -->
                <view class="merchant-footer">
                  <view class="quota-info">
                    <text class="info-label">申请名额</text>
                    <text class="info-value">{{ item.period.fullNumberOfPeople }}人/{{ item.period.fullNumberOfRegiment
                      }}团</text>
                  </view>
                  <button class="action-button" :data-id="item.period.id" :data-merchantId="it.targetMerchantId"
                    :data-relationId="it.id" :data-goType="'报名详情'" @tap="goItem">查看详情</button>
                </view>
              </block>
            </view>
          </block>
        </view>

        <!-- 已拒绝列表 -->
        <view v-if="isDate.id && rGroup.length > 0" class="section">
          <view class="section-header">
            <view class="header-content header-content-bold">
              <!-- <image class="header-icon-small" role="img" src="https://wxapi.qctrips.cn/yx/images/goods/date.png" mode="" />-->
              <text>已拒绝审批</text>
            </view>
          </view>

          <!-- 已拒绝审批信息列表 -->
          <block v-for="item in rGroup" :key="item.id">
            <view class="merchant-info-section">
              <block v-for="(it, idx) in item.JuThroughNumber" :key="idx">
                <!-- 分隔线（非首项时显示） -->
                <view v-if="idx !== 0" class="section-divider"></view>

                <!-- 商家基本信息 -->
                <view class="merchant-header">
                  <view class="merchant-type-tag">{{ item.StandbyFieldThree || '组团' }}</view>
                  <text class="merchant-name-text">{{ it.merchantDTO.name }}</text>
                </view>

                <!-- 客源城市信息 -->
                <view class="info-row">
                  <text class="info-label">客源城市</text>
                  <text class="info-value">{{ item.Address }}此处暂无</text>
                </view>

                <!-- 申请名额和操作按钮 -->
                <view class="merchant-footer">
                  <view class="quota-info">
                    <text class="info-label">申请名额</text>
                    <text class="info-value">{{ item.period.fullNumberOfPeople }}人/{{ item.period.fullNumberOfRegiment
                      }}团</text>
                  </view>
                  <button class="action-button" :data-id="item.period.id" :data-merchantId="it.targetMerchantId"
                    :data-relationId="it.id" :data-goType="'报名详情'" @tap="goItem">查看详情</button>
                </view>
              </block>
            </view>
          </block>
        </view>

        <!-- 取消申请列表 -->
        <view v-if="isDate.id && qGroup.length > 0" class="section">
          <view class="section-header">
            <view class="header-content header-content-bold">
              <!-- <image class="header-icon-small" role="img" src="https://wxapi.qctrips.cn/yx/images/goods/date.png" mode="" /> -->
              <text>取消申请</text>
            </view>
          </view>

          <!-- 取消申请信息列表 -->
          <block v-for="item in qGroup" :key="item.id">
            <view class="merchant-info-section">
              <!-- 商家基本信息 -->
              <view class="merchant-header">
                <view class="merchant-type-tag">{{ item.StandbyFieldThree || '组团' }}</view>
                <text class="merchant-name-text">{{ item.merchantDTO?.name || '未知商家' }}</text>
              </view>

              <!-- 客源城市信息 -->
              <view class="info-row">
                <text class="info-label">客源城市</text>
                <text class="info-value">{{ item.Address }}此处暂无</text>
              </view>

              <!-- 申请名额和操作按钮 -->
              <view class="merchant-footer">
                <view class="quota-info">
                  <text class="info-label">申请名额</text>
                  <text class="info-value">{{ item.period?.fullNumberOfPeople || 0 }}人/{{
                    item.period?.fullNumberOfRegiment || 0
                    }}团</text>
                </view>
                <button class="action-button" :data-id="item.period?.id || 0"
                  :data-merchantId="item.targetMerchantId || 0" :data-relationId="item.id || 0" :data-goType="'报名详情'"
                  @tap="goItem">查看详情</button>
              </view>
            </view>
          </block>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { request } from '../../utils/request';
import { mergeAllProducts } from '../../utils/productUtil.js';
import DateCard from '../../components/DateCard';
import ProductCard from '../../components/ProductCard.vue'

export default {
  components: {
    DateCard,
    ProductCard
  },
  data() {
    return {
      StatusBar: 0,
      TabbarBot: 0,
      backgroundColor: 'var(--blue)',
      checkbox_tag: [],
      feilv: 0.06,
      fold: false,
      info: [],
      datelist: [],
      isDate: {},
      CPId: -1,
      wGroup: [], // 待审批
      jGroup: [], // 已同意
      rGroup: [], // 已拒绝
      qGroup: [], // 取消申请
      productInfo: {},
      periodListGet: []
    }
  },
  onLoad(options) {
    if (options.id) {
      this.CPId = options.id;
      this.getPeriod();
      this.getInfo();
    }
  },
  onShow() {
    this.getPeriod();
  },
  methods: {
    dateChange(e) {
      console.log(e);
      let element = e;
      this.isDate = element;
      let wP = [];
      let jP = [];
      let rP = [];
      let qP = [];

      if (element.DaiThroughNumber && element.DaiThroughNumber.length > 0) {
        wP.push(element);
      }
      if (element.ThroughNumber && element.ThroughNumber.length > 0) {
        jP.push(element);
      }
      if (element.JuThroughNumber && element.JuThroughNumber.length > 0) {
        rP.push(element);
      }
      if (element.ApplyStatus == "取消申请") {
        qP.push(element);
      }
      this.wGroup = wP;
      this.jGroup = jP;
      this.rGroup = rP;
      this.qGroup = qP;
    },
    async getPeriod() {
      try {
        const companyInfo = uni.getStorageSync('companyInfo') || {};
        const res = await request({
          url: `/period-sku/getPeriods?spuId=${this.CPId}&merchantId=${companyInfo.id || ''}&merchantType=${companyInfo.businessType || ''}`,
          method: 'GET'
        });

        if (res.code == 200) {
          let periodListGet = res.data;
          periodListGet.forEach(item => {
            const { p1s, p2s, p3s } = item;
            if (companyInfo.businessType == 3) {
              item.main = p3s;
            }
            if (companyInfo.businessType == 2) {
              item.main = p2s;
            }
            if (companyInfo.businessType == 1) {
              item.main = p1s;
            }
          });

          let mainInfo = periodListGet[0]?.main[0];
          let datelist = [];

          if (periodListGet[0]?.main) {
            periodListGet[0].main.forEach(dateItem => {
              const dateInfo = dateItem.availableDate;
              let date = {
                DateName: '',
                date: '',
                Datevalue: '',
                Datevalue1: '',
                WeekName: '',
                id: 0
              };
              date.id = dateItem.id;
              date.DateName = `${dateInfo.yearDate}-${dateInfo.monthDate}-${dateInfo.dayDate}`;
              date.date = `${dateInfo.monthDate}-${dateInfo.dayDate}`;
              date.Datevalue = `${dateInfo.yearDate}-${dateInfo.monthDate}-${dateInfo.dayDate}`;
              date.Datevalue1 = `${dateInfo.monthDate}-${dateInfo.dayDate}`;
              date.WeekName = dateInfo.weekDate;
              datelist.push(date);
            });
          }

          this.datelist = datelist;
          this.periodListGet = periodListGet;
          this.mainInfo = mainInfo;
          this.getApplyList();
        } else {
          uni.showToast({
            title: '获取信息失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取班期信息失败:', error);
        uni.showToast({
          title: '获取信息失败',
          icon: 'none'
        });
      }
    },
    async getInfo() {
      try {
        const companyInfo = uni.getStorageSync('companyInfo') || {};
        const res = await request({
          url: `/product-spu/getProduct?id=${this.CPId}&merchantType=${companyInfo.businessType || ''}`,
          method: 'GET'
        });
        console.log('获取产品信息', res);
        if (res.code == 200) {
          const productInfo = mergeAllProducts([res.data], companyInfo.businessType);
          this.productInfo = productInfo[0];
          console.log('this.product', this.productInfo);
        } else {
          uni.showToast({
            title: '获取信息失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取产品信息失败:', error);
        uni.showToast({
          title: '获取信息失败',
          icon: 'none'
        });
      }
    },
    async getApplyList() {
      const periodListGet = this.periodListGet[0]
      try {
        const res = await request({
          url: `/call-apply/list/${this.CPId}`,
          method: 'GET'
        });

        if (res.code == 200) {
          let datelist = this.datelist;
          datelist.forEach(i => {
            i.DaiThroughNumber = [];
            i.ThroughNumber = [];
            i.JuThroughNumber = [];
            i.period = {};
          });
          res.data.forEach(item => {
            datelist.forEach(date => {
              console.log('item.status', item.status);

              if (date.id == item.sourcePeriodId) {
                if (item.status == '申请中') {
                  date.DaiThroughNumber.push(item)
                }
                if (item.status == '已同意') {
                  date.ThroughNumber.push(item)
                }
                if (item.status == '已拒绝') {
                  date.JuThroughNumber.push(item)
                }
              }
            });
          });
          console.log('periodListGet', periodListGet);
          periodListGet.main.forEach(item => {
            datelist.forEach(i => {
              if (i.id == item.id) {
                i.period = item;
              }
            });
          });
          this.datelist = datelist;
        }
      } catch (error) {
        console.error('获取申请列表失败:', error);
      }
    },
    goItem(e) {
      console.log('e', e);

      const { id, gotype, merchantid, relationid } = e.currentTarget.dataset;
      uni.navigateTo({
        url: `/public/campManagement/campItemInfo?id=${id}&goType=${gotype}&merchantId=${merchantid}&relationId=${relationid}`
      });
    },
    BackPage() {
      uni.navigateBack();
    },
    toHome() {
      uni.switchTab({
        url: '/pages/customer/index/index'
      });
    }
  }
}
</script>

<style scoped>
.content-area {}

/* 主容器样式 */
.camp-management-container {
  background-color: #f7f7f7;
  min-height: 100vh;
  padding-bottom: 100rpx;
}

/* 内容容器样式 */
.content-container {
  padding: 20rpx;
}

/* 通用区块样式 */
.section {
  margin-top: 20rpx;
  background-color: white;
  border-radius: 10rpx;
  padding: 20rpx;
}

/* 区块头部样式 */
.section-header {
  padding: 15rpx 0;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header-wrap {
  background-color: white;
  padding: 15rpx 0;
}

.header-full {
  width: 100%;
  display: flex;
  justify-content: start;
}

.header-content {
  display: flex;
  align-items: center;
}

.header-content-bold {
  font-weight: bold;
}

.header-icon {
  width: 40rpx;
  height: 40rpx;
  margin-left: -10rpx;
}

.header-icon-small {
  width: 20px;
  height: 20px;
  margin-left: -10rpx;
}

.selected-date-text {
  margin-left: 130rpx;
  color: #333;
}

/* 商家信息区块样式 */
.merchant-info-section {
  background-color: white;
  border-radius: 10rpx;
  padding: 15rpx;
  margin-top: 15rpx;
}

.section-divider {
  width: 100%;
  height: 1px;
  background-color: #eee;
  margin: 20rpx 0;
}

/* 商家头部信息样式 */
.merchant-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.merchant-type-tag {
  background-color: #e6f3ff;
  color: #0782c1;
  padding: 6rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.merchant-name-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 信息行样式 */
.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.info-label {
  color: #666;
  font-size: 28rpx;
}

.info-value {
  color: #333;
  font-size: 28rpx;
}

/* 商家底部样式 */
.merchant-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10rpx;
}

/* 配额信息样式 */
.quota-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 300rpx;
}

/* 操作按钮样式 */
.action-button {
  background-color: #0782c1;
  color: white;
  border: none;
  border-radius: 30rpx;
  font-size: 24rpx;
  margin: 0;
}

.action-button:active {
  background-color: #066c9c;
}
</style>
